import { Component } from "react";
// 1.评论样式
import './index.css'
import dayjs from 'dayjs' 
// import avatar from "./images/avatar.png";
import Tab from "./components/tab"
import Form from "./components/form";
import List from "./components/list";
class App extends Component {
  // 2.data数据
  state = {
  // hot: 热度排序  time: 时间排序
  tabs: [
    {
      id: 1,
      name: '热度',
      type: 'hot'
    },
    {
      id: 2,
      name: '时间',
      type: 'time'
    }
  ],
  // 当前选中页签的标识
  active: 'hot',
  list: [
    {
      id: 1,
      author: '刘德华',
      comment: '给我一杯忘情水',
      time: new Date('2021-10-10 09:09:00'),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 1
    },
    {
      id: 2,
      author: '周杰伦',
      comment: '哎哟，不错哦',
      time: new Date('2021-10-11 09:09:00'),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 0
    },
    {
      id: 3,
      author: '五月天',
      comment: '不打扰，是我的温柔',
      time: new Date('2021-10-11 10:09:00'),
      // 1: 点赞 0：无态度 -1:踩
      attitude: -1
    }
  ],
  content: ''
}
// 格式化时间
 time=(time)=>{
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}
componentDidUpdate(){
  localStorage.setItem('list',JSON.stringify(this.state.list))
}
componentDidMount(){
  this.setState({
    list:JSON.parse( localStorage.getItem('list'))||this.state.list
  })
}
// tab栏切换功能
changeFlag=(type)=>{
  this.setState({
    active:type
  })
}

// 删除
delList=(id)=>{
  this.setState({
    list:this.state.list.filter(item=>item.id!==id)
  })
}
// handleChange=(e)=>{
// this.setState({
//   content:e.target.value
// })
// }
// 添加
addList=(content)=>{
  const newComment= {
    id: Date.now(),
    author: '作者',
    comment: content,
    time: new Date(),
    // 1: 点赞 0：无态度 -1:踩
    attitude: 0,
  }
  this.setState({
    list:[
      ...this.state.list,
      newComment
    ],
    content: ''
  })
}

// 点赞状态的切换
changeAttitude=(id,attitude)=>{
  console.log(id,attitude);
this.setState({
  list:this.state.list.map(item=>{
    if (item.id===id) {
      return{
        ...item,
        attitude
      }
    }else{
      return{
        ...item
      }
    }
  })
})
}

// 3.html结构
render(){
  return(
    <div className="App">
    <div className="comment-container">
      {/* 评论数 */}
      <div className="comment-head">
        <span>{this.state.list.length}评论</span>
      </div>
      {/* 排序 */}
      <Tab tabs={this.state.tabs} changeFlag={this.changeFlag} active={this.state.active}/>

      {/* 添加评论 */}
      <Form handleChange={this.handleChange} addList={this.addList}></Form>

      {/* 评论列表 */}
    <List list={this.state.list} delList={this.delList} changeAttitude={this.changeAttitude}/>
    </div>
  </div>
  )
}
}



export default App

